package com.gao.future;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步调用：CompletableFuture
 * 1、 异步执行
 * 2、 成功回调
 * 3、 失败回调
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

////        无返回值的runAsync异步回调
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
////            模拟网络请求延迟
//            try {
//                TimeUnit.SECONDS.sleep(0);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println(Thread.currentThread().getName() + "runAsync => Void");
//        });
//
//        System.out.println("1111111111");
//
////        获取异步执行结果，会产生阻塞。
//        completableFuture.get();

//        有返回值的runAsync异步回调
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync => Integer");
            int i = 10/0;
            return 1024;
        });

        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t => " + t);
            System.out.println("u => " + u);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233;
        }).get());

    }
}
